package com.feixiang.springbootinit.controller;
import cn.hutool.json.JSONUtil;
import com.feixiang.springbootinit.utils.mp.aes.WXBizJsonMsgCrypt;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/wechat")
@RestController
@Slf4j
/**
 * 企微回调地址
 */
public class WeChatController {
    @GetMapping("/message/callback")
    @ResponseBody()
    public String callback(HttpServletRequest request, @RequestParam("msg_signature") String sVerifyMsgSig, @RequestParam("timestamp") String sVerifyTimeStamp, @RequestParam("nonce") String sVerifyNonce, @RequestParam("echostr") String sVerifyEchoStr) throws Exception {

        String sToken = "";
        String sCorpID = "";
        String sEncodingAESKey = "";
        WXBizJsonMsgCrypt wxcpt = new WXBizJsonMsgCrypt(sToken, sEncodingAESKey, sCorpID);
        String sEchoStr; //需要返回的明文
        try {
            sEchoStr = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp,
                    sVerifyNonce, sVerifyEchoStr);
            return sEchoStr;
            // 验证URL成功，将sEchoStr返回
            // HttpUtils.SetResponse(sEchoStr);
        } catch (Exception e) {
            //验证URL失败，错误原因请查看异常
            e.printStackTrace();
        }
        return "error";
    }

    @PostMapping("/message/callback")
    @ResponseBody()
    public void callbackData(HttpServletRequest request, @RequestBody() String sRespData, @RequestParam("msg_signature") String sVerifyMsgSig, @RequestParam("timestamp") String sReqTimeStamp, @RequestParam("nonce") String sReqNonce) throws Exception {
        String sToken = "";
        String sCorpID = "";
        String sEncodingAESKey = "";
        WXBizJsonMsgCrypt wxcpt = new WXBizJsonMsgCrypt(sToken, sEncodingAESKey, sCorpID);
        String sMsg = wxcpt.DecryptMsg(sVerifyMsgSig, sReqTimeStamp, sReqNonce, sRespData);
        System.out.println("解密decrypt企业微信推送的消息->sMsg：" + sMsg);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        StringReader sr = new StringReader(sMsg);
        InputSource is = new InputSource(sr);
        Document document = db.parse(is.getByteStream());
        //获取整个XML消息体，进行解析
        Element root = document.getDocumentElement();
        //返回消息的公共部分，内容，创建时间，消息ID，来源，去处
        NodeList nodelistTime = root.getElementsByTagName("CreateTime");
        String CreateTime = nodelistTime.item(0).getTextContent();
        NodeList nodelistFrom = root.getElementsByTagName("FromUserName");
        String fromUserName = nodelistFrom.item(0).getTextContent();
        NodeList nodelistTo = root.getElementsByTagName("ToUserName");
        String toUserName = nodelistTo.item(0).getTextContent();
        Map<String, String> msgMap = new HashMap<String, String>();
        msgMap.put("CreateTime", CreateTime);
        msgMap.put("fromUser", fromUserName);
        msgMap.put("to", toUserName);
        //消息类型，不同消息返回不同消息体
        NodeList typeNodelist = root.getElementsByTagName("MsgType");
        String MsgType = typeNodelist.item(0).getTextContent();
        msgMap.put("msgType", MsgType);
        //文本直接返回
        if (StringUtils.equals(MsgType, "text")) {
            NodeList nodelistMsgId = root.getElementsByTagName("MsgId");
            String MsgId = nodelistMsgId.item(0).getTextContent();
            msgMap.put("msgId", MsgId);
            NodeList nodelist = root.getElementsByTagName("Content");
            String Content = nodelist.item(0).getTextContent();
            msgMap.put("text", Content);
            //自定义返回消息类型，只支持字符串类型
            Map<String, Object> getMsg = new HashMap<String, Object>();
            getMsg.put("msg", msgMap);
            //使用hutools
            String message = JSONUtil.toJsonStr(getMsg);
            //String message = JSONArray.toJSON(getMsg).toString();
            log.info("发送消息：{}", message);
            //返回给前端消息
            //rabbitTemplate.convertAndSend("qywx_exange", null, message);
            //图片返回图片需要增加url和mediaId
            //todo
        }
    }
}
